package com.atguigu.controller;

import com.atguigu.common.R;
import com.atguigu.entity.Category;
import com.atguigu.service.impl.CategoryServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {
    @Resource
    private CategoryServiceImpl categoryService;

    //添加分类
    @PostMapping
    public R<String> add(@RequestBody Category category) {
        log.info(category.toString());
        categoryService.save(category);
        return R.success("新增菜品成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        log.info("page=" + page + "pageSize=" + pageSize);
        Page<Category> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //条件排序
        queryWrapper.orderByAsc(Category::getSort);
        //分页查询
        categoryService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 删除分类信息
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(String ids) {
        log.info("ids=" + ids);
        //categoryService.removeById(ids);
        categoryService.myRemove(ids);
        return R.success("删除分类信息成功");
    }

    /**
     * 修改分类
     *
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        log.info(category.toString());
        categoryService.updateById(category);
        return R.success("分类修改成功");
    }

    /**
     * 根据条件分类显示菜品
     *
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> showDish(Category category) {
        log.info(category.toString());
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //根据菜品类型匹配相应的菜品
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        //添加排序条件
        queryWrapper.orderByAsc(Category::getSort);
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }

}
